package warmachineroster.service.validation.calculators;

import warmachineroster.service.validation.UnitCounter;
import warmachinesystem.BaseUnit;

public class StructureCalculator {

	public boolean calculateStructuralValidity(UnitCounter unitCounter, TierStatus status) {
		boolean validStructure = true;
		for (BaseUnit bu : unitCounter.getUnits()) {
			String fa;
			fa = getUnitFa(bu, status);

			if ("U".equals(fa)) {
				continue;
			} else if ("C".equals(fa)) {
				if (unitCounter.getCount(bu) > 1)
					validStructure = false;
			} else {
				Integer intFa = Integer.valueOf(fa);
				validStructure = intFa.compareTo(unitCounter.getCount(bu)) >= 0;
			}
			if (!validStructure) {
				break;
			}
		}
		return validStructure;
	}

	private String getUnitFa(BaseUnit bu, TierStatus status) {
		String fa;
		if (status.getUnitFaDelta().get(bu) != null) {
			if ("U".equals(status.getUnitFaDelta().get(bu))){
				return status.getUnitFaDelta().get(bu);
			}
			try{
				int faDelta = Integer.parseInt(status.getUnitFaDelta().get(bu));
				fa = bu.getFieldAllowance();
				int baseFa = Integer.parseInt(fa);
				fa = String.valueOf(baseFa + faDelta);
			}catch(Exception e){
				fa = bu.getFieldAllowance();
			}
		} else {
			fa = bu.getFieldAllowance();
		}
		return fa;
	}
	
}
